#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include "app_common.h"


int sqrt_num(int num)
{
     sleep(1);
     return num*num;
}


void *sqrt_num_thread(void *arg)
{
    sleep(1);
    //1 强转
    int *num_p =  (int *)arg;
    //2  解引用 取值
    int num = *num_p;
    //3 计算
    int res =  num*num;
    //4 开空间 
    int *res_p = (int *)malloc(sizeof(int));
    //5 指向值
    *res_p = res;
    return res_p;
}


int main(int argc, char const *argv[])
{
    int nums[5]={1,2,3,4,5};
    int res[5];
    int sum=0;
    long start_ts= app_common_get_cur_ts();
    //计算每个数的平方值
    pthread_t threads[5];
    for (size_t i = 0; i < 5; i++)
    {
       // res[i] =sqrt_num(nums[i]);
        pthread_create(&threads[i],NULL,sqrt_num_thread,&nums[i]);
    }
    for(size_t i = 0; i < 5; i++)
    {   void *res_p;
        pthread_join(threads[i], &res_p);
        // 强转
        int *res_p_int = (int *)res_p;
        // 解引用 取值
        res[i] = *res_p_int;
    }


    //把计算结果汇总
    for (size_t i = 0; i < 5; i++)
    {
        sum+=res[i];
    }
    long end_ts= app_common_get_cur_ts();
    printf("cost=%ld\n",end_ts-start_ts);
    printf("sum=%d\n",sum);

    return 0;
}


